
package com.loan.rebate.pictures.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.loan.rebate.common.controller.BaseController;
import com.loan.rebate.common.param.SessionUserInfo;
import com.loan.rebate.config.ConfigUtils;
import com.loan.rebate.pictures.entity.PicturesVO;
import com.loan.rebate.pictures.service.PicturesService;

/**
 * 系统图片信息Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class PicturesController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(PicturesController.class);

    @Autowired
    private PicturesService picturesService;
    
    @RequestMapping(value = "/check/pictures/upload", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, Integer pictureType, String pictureRemark,
        HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        SessionUserInfo seUser = (SessionUserInfo) getSession(request).getAttribute("sessionUserInfo");
        if (seUser == null || StringUtils.isBlank(seUser.getUserId())) {
            resultMap.put("result", false);
            resultMap.put("message", "session超时请重新登录");
            return JSONObject.toJSONString(resultMap);
        }
        if (file == null) {
            resultMap.put("result", false);
            resultMap.put("message", "请先选择要上传的图片");
            return JSONObject.toJSONString(resultMap);
        }
        
        Long fileSize = file.getSize();

        if (pictureType != null && pictureType == 1 && fileSize > 30720) {
            logger.error("图片上传失败，头像图片不能超过30K");
            resultMap.put("result", false);
            resultMap.put("message", "新增上传出错：头像图片超过30K");
            return JSONObject.toJSONString(resultMap);
        } else if (fileSize > 1048576) {
            logger.error("图片上传失败，图片不能超过1M");
            resultMap.put("result", false);
            resultMap.put("message", "新增上传出错：图片不能超过1M");
            return JSONObject.toJSONString(resultMap);
        }

        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String fileId = UUID.randomUUID().toString().replace("-", "");
        String folder = fileId.substring(0, 4);
        String basepath = ConfigUtils.getStringValueByKey("picture.store_path");
        File targetFile = new File(basepath + File.separator + folder, fileId + "." + suffix);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            logger.error("图片上传失败", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增上传出错：" + e.getLocalizedMessage());
            return JSONObject.toJSONString(resultMap);
        }

        try {

            PicturesVO picturesVO = new PicturesVO();
            picturesVO.setPictureId(fileId);
            picturesVO.setCreateUser(seUser.getUserId());
            String pictureName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
            picturesVO.setPictureName(pictureName);
            picturesVO.setPicturePath(File.separator + folder);
            picturesVO.setPictureRemark(pictureRemark);
            picturesVO.setPictureSuffix(suffix);
            picturesVO.setPictureType(pictureType);
            Integer insertCount = picturesService.insert(picturesVO);
            if (insertCount != null && insertCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增图片信息成功");
                resultMap.put("pictureId", fileId);
                return JSONObject.toJSONString(resultMap);
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增图片信息失败");
                return JSONObject.toJSONString(resultMap);
            }
        } catch (Exception e) {
            logger.error("新增或修改系统图片信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增图片信息出错：" + e.getLocalizedMessage());
            return JSONObject.toJSONString(resultMap);
        }
    }

    @RequestMapping(value = "/uncheck/pictures/upload/json", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public String upload(@RequestParam(value = "imgFile", required = false) MultipartFile imgFile, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        if (imgFile == null) {
            resultMap.put("result", false);
            resultMap.put("message", "请先选择要上传的图片");
            return JSONObject.toJSONString(resultMap);
        }

        Long fileSize = imgFile.getSize();

        if (fileSize > 1048576) {
            logger.error("图片上传失败，图片不能超过1M");
            resultMap.put("error", 1);
            resultMap.put("message", "新增上传出错：图片不能超过1M");
            return JSONObject.toJSONString(resultMap);
        }

        String suffix = imgFile.getOriginalFilename().substring(imgFile.getOriginalFilename().lastIndexOf(".") + 1);
        String fileId = UUID.randomUUID().toString().replace("-", "");
        String folder = fileId.substring(0, 4);
        String basepath = ConfigUtils.getStringValueByKey("picture.store_path");
        File targetFile = new File(basepath + File.separator + folder, fileId + "." + suffix);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 保存
        try {
            imgFile.transferTo(targetFile);
        } catch (Exception e) {
            logger.error("图片上传失败", e);
            resultMap.put("error", 1);
            resultMap.put("message", "新增上传出错：" + e.getLocalizedMessage());
            return JSONObject.toJSONString(resultMap);
        }

        try {
            SessionUserInfo seUser = (SessionUserInfo) getSession(request).getAttribute("sessionUserInfo");
            PicturesVO picturesVO = new PicturesVO();
            picturesVO.setPictureId(fileId);
            picturesVO.setCreateUser(seUser.getUserId());
            String pictureName = imgFile.getOriginalFilename().substring(0, imgFile.getOriginalFilename().lastIndexOf("."));
            picturesVO.setPictureName(pictureName);
            picturesVO.setPicturePath(File.separator + folder);
            picturesVO.setPictureSuffix(suffix);
            Integer insertCount = picturesService.insert(picturesVO);
            if (insertCount != null && insertCount == 1) {
                resultMap.put("error", 0);
                resultMap.put("message", "新增图片信息成功");
                resultMap.put("url", request.getContextPath() + "/uncheck/pictures/servlet?id=" + fileId);
                return JSONObject.toJSONString(resultMap);
            } else {
                resultMap.put("error", false);
                resultMap.put("message", "新增图片信息失败");
                return JSONObject.toJSONString(resultMap);
            }
        } catch (Exception e) {
            logger.error("新增或修改系统图片信息出错", e);
            resultMap.put("error", 1);
            resultMap.put("message", "新增图片信息出错：" + e.getLocalizedMessage());
            return JSONObject.toJSONString(resultMap);
        }
    }
}
